<script setup lang="ts">

import {ref, computed} from "vue";
import {register} from "@/api/sysController.ts";
import {Message} from "@arco-design/web-vue";
import {useWindowSize} from "@vueuse/core/index";

const visible = ref<boolean>(false)
const userRef = ref()

const { width } = useWindowSize()
const isPhone = computed(() => {
  return width.value < 768
})

const open = () => {
  visible.value = true
}

const user = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const rules = {
  username: [
    {required: true, message: '请输入用户名'}
  ],
  password: [
    {required: true, message: '请输入密码'},
      // 支持8到16位数字、字母
    {match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/, message: '密码格式不正确，支持8到16位数字、字母'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入密码'},
    {validator: (rule, value, callback) => {
      if (value !== user.value.password) {
        callback('两次输入密码不一致')
      } else {
        callback()
      }
    }}
  ]
}

const confirm = async () => {
  return new Promise<any>((resolve, reject) => {
    userRef.value.validate((error) => {
      if (!error) {
        register(user.value.username, user.value.password).then(res => {
          if(res) {
            resolve(true)
            Message.success('注册成功, 请联系管理员激活账号')
            visible.value = false
            userRef.value.resetFields()
          } else {
            Message.error('注册失败')
            reject(false)
          }
        }).catch(err => {
          reject(false)
        })
      } else {
        reject(error)
      }
    })
  })
}

defineExpose({open})
</script>

<template>
  <a-modal v-model:visible="visible" title="注册账号" :on-before-ok="confirm" :width="isPhone ? '90vw' : undefined">
    <a-form ref="userRef" :model="user" :rules="rules" :layout="isPhone ? 'vertical' : 'horizontal'">
      <a-form-item label="账号" field="username">
        <a-input v-model="user.username"></a-input>
      </a-form-item>
      <a-form-item label="密码" field="password">
        <a-input-password v-model="user.password" placeholder="请输入8到16位数字、字母组成的密码" ></a-input-password>
      </a-form-item>
      <a-form-item label="确认密码" field="confirmPassword">
        <a-input-password v-model="user.confirmPassword" placeholder="请再输入一次密码" ></a-input-password>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="scss">
@media (max-width: 768px) {
  :deep(.arco-modal) {
    max-width: 90vw;
  }

}
</style>
